package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Car;
import com.joint.core.entity.manage.CarConfig;
import com.joint.core.service.CarConfigService;
import com.joint.core.service.CarService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/21.
 */
@ParentPackage("manage")
public class AjaxCarAction extends BaseFlowAction {
    @Resource
    private DutyService dutyService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private CarService carService;
    @Resource
    private CarConfigService carConfigService;

    /**
     * 车辆配置表
     */
    private CarConfig carConfig;
    private List<Map<String, Object>> carConfigList;
    private String carConfigId;
    /**
     * 详细说明
     */
    private String description;
    /**
     * 附件
     */
    private String fileId;
    private String fileIds;
    /**
     * 使用时间
     */
    private String dateStart;
    private String dateEnd;
    /**
     * 当前公里数
     */
    private int kilometre;
    private int kilometreNum;
    /**
     * 备注
     */
    private String remarks;
    /**
     * 申请用途
     */
    private String purpose;
    /**
     * 新建时判断
     */
    private int isUse;

    private Car car;
    private Users loginUser;
    private int numStatus;
    private String step;

    private String carNoId1;
    private String carNoId3;
    private String dateStart1;

    public String execute(){
        return "car";
    }

    public String list(){
        pager = new Pager(0);
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
       // params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(step)){
            if(step.equals("1")){
                //申请中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("step", "1");
                pager=carService.findByPagerAndLimit(false, "car", pager, params);
            }else if(step.equals("2")){
                //待使用
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("step", "2");
                pager=carService.findByPagerAndFinish( "car", pager, params);
            }else if(step.equals("3")){
                //已使用
                params.put("step", "3");
                pager=carService.findByPagerAndLimit(true, "car", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished});
            pager=carService.findByPagerAndLimit(true, "car", pager, params);
            if(StringUtils.isNotEmpty(carNoId3)){
                CarConfig carConfig=carConfigService.get(carNoId3);
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished});
                params.put("carConfig",carConfig);
                pager=carService.findByPagerAndLimit(true, "car", pager, params);
            }
        }

        List<Car> carList;
        if (pager.getTotalCount() > 0){
            carList = (List<Car>) pager.getList();
        }else{
            carList= new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Car car: carList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",car.getId());
            rMap.put("creater", car.getCreater() != null ? car.getCreater().getName() : "");
            rMap.put("use", car.getPurpose());
            rMap.put("brand",car.getCarConfig().getBrand());
            rMap.put("type",car.getCarConfig().getType());
            rMap.put("carNo",car.getCarConfig().getCarNo());
            String time=DataUtil.DateToString(car.getDateStart(),"yyyy-MM-dd")+"~"+DataUtil.DateToString(car.getDateEnd(),"yyyy-MM-dd");
            rMap.put("time",time);
            rMap.put("state",car.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            fileId ="";
            car = carService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            if(car.getFile() != null && car.getFile().size()>0){
                for(FileManage f:car.getFile()){
                    fileId+=f.getId()+",";
                }
            }

        }
        return "read";
    }

    public String input(){
        Company company = usersService.getCompanyByUser();
        Map<String,Object> rMap = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("processState", new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished});
        List<CarConfig> list = (List<CarConfig>)carConfigService.findByPagerAndCompany(null, null, company, params).getList();
        carConfigList = new ArrayList<Map<String, Object>>();
        if (StringUtils.isNotEmpty(keyId)){
            fileId ="";
            car = carService.get(keyId);
            if(car.getFile() != null && car.getFile().size()>0){
                for(FileManage f:car.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            for(CarConfig carConfig:list){
                rMap = new HashMap<String, Object>();
                rMap.put("id",carConfig.getId());
                rMap.put("name",carConfig.getCarNo());
                rMap.put("selected","");
                if(car.getCarConfig()!=null && StringUtils.equals(carConfig.getId(), car.getCarConfig().getId())){
                    rMap.put("selected","selected");
                }
                carConfigList.add(rMap);
            }
        } else {
            if(list.size()>0){
                for(CarConfig carConfig:list){
                    rMap = new HashMap<String, Object>();
                    rMap.put("id",carConfig.getId());
                    rMap.put("name",carConfig.getCarNo());
                    rMap.put("selected","");
                    carConfigList.add(rMap);
                }
            }
        }
        return "input";
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            car=carService.get(keyId);
        }else{
            car=new Car();
            car.setCreater(usersService.getLoginInfo());
        }
        car.setCarConfig(carConfigService.get(carConfigId));
        car.setPurpose(purpose);
        car.setDescription(description);
        car.setDateStart(DataUtil.StringToDate(dateStart));
        car.setDateEnd(DataUtil.StringToDate(dateEnd));
        car.setRemarks(remarks);
        car.setCompany(usersService.getLoginInfo().getCompany());
        car.setKilometre(kilometre);
        car.setStep("1");
        car.setIsUse(isUse);
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManageService.get(f.trim()));
            }
        }
        car.setFile(fileManageList);
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                carService.update(car);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                carService.save(car, "car", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    //判断选择的车辆是否被正在使用
    public String checkuse(){
        String isUse="";
        List<JSONObject> dataRow = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        CarConfig carConfig=carConfigService.get(carConfigId);
        Date date=DataUtil.StringToDate(dateStart1);
        Users user=usersService.getLoginInfo();
        boolean check=carService.checkUse(carConfig,date,user);
        if(check){
            isUse="1";
        }else{
            isUse="0";
        }
        map.put("check", isUse);
        dataRow.add(JSONObject.fromObject(map));
        data.put("data", JSONArray.fromObject(dataRow));
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    /**
     * 获取车辆数据
     */
    public String getInfo(){
        Map<String, Object> map = new HashMap<String, Object>();
        if(StringUtils.isNotEmpty(carConfigId)){
            carConfig=carConfigService.get(carConfigId);
            map.put("brand",carConfig.getBrand());
            map.put("type",carConfig.getType());
        }
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(map));
    }

    // 提交
    public String commit(){
        setData();
        Company company = usersService.getCompanyByUser();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        List<Users> carAdmin=Lists.newArrayList();
        List<String> caradminList=Lists.newArrayList();
        Set<Duty> dutySet=usersService.getLoginInfo().getDutySet();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Department> deptSet=dept.getChildren();
            for(Department cdept:deptSet){
                Set<Power> powers = cdept.getPowerSet();
                for(Power power:powers){
                    System.out.println(power.getPost().getName());
                    if(power.getPost().getName().equals("车辆管理员")){
                        List<Users> usersList=dutyService.getPersons(cdept,power.getPost());
                        for(Users user:usersList){
                            carAdmin.add(user);
                            caradminList.add(user.getId().trim());
                        }
                    }
                }

            }
        }
        var2.put("caradmin", caradminList);
        car.setCarAdmin(carAdmin);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                carService.approve(car, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = carService.commit(car, "car", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批1
    public String approve1(){
        car = carService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus", 2);
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                carService.approve(car, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        } catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批2
    public String approve2(){
        car = carService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);
        var1.put("numStatus",3);
        car.setStep("2");
        carService.update(car);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                carService.approve(car, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        } catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            car = carService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("car");
            String key=activityList.get(0).getId();
            if(StringUtils.isEmpty(comment)) comment="";
            carService.reject(car, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            car = carService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("car");
            String key= activityList.get(activityList.size()-1).getId();
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            carService.deny(car, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    /**
     * 当前公里数登记
     * @return
     */
    public String qkilometre(){
        boolean isChange=false;
        if(StringUtils.isNotEmpty(keyId)){
            car=carService.get(keyId);
            List<Users> usersList=car.getCarAdmin();
            for(Users user:usersList){
                if(user.getId().equals(usersService.getLoginInfo().getId())){//判断当前登录的人和被选择的条目是否有关系
                    isChange=true;
                    break;
                }
            }
//            Set<Duty> dutySet=car.getCreater().getDutySet();
//            for(Duty duty:dutySet){
//                Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
//                Set<Department> deptSet=dept.getChildren();
//                for(Department cdept:deptSet){
//                    Set<Power> powers = cdept.getPowerSet();
//                    for(Power power:powers){
//                        if(power.getPost().getName().equals("车辆管理员")){//判断当前登录的车辆管理员和被选择的条目是否有关系
//                            List<Users> usersList=dutyService.getPersons(cdept,power.getPost());
//                            for(Users user:usersList){
//                                if(user.getId().equals(usersService.getLoginInfo().getId())){
//                                    System.out.println("###修改了数据！！！！");
//                                    isChange=true;
//                                    break;
//                                }
//                            }
//                        }
//                    }
//
//                }
//            }
        }
        if(isChange){
            int oldKilometre=car.getKilometre();
            int newKilometre=oldKilometre+kilometreNum;
            car.setKilometre(newKilometre);
            carService.update(car);
            return ajaxHtmlCallback("200", "提交成功！", "操作状态");
        }else{
            return ajaxHtmlCallback("400", "没有权限！", "操作状态");
        }

    }


    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public String getDateStart() {
        return dateStart;
    }

    public void setDateStart(String dateStart) {
        this.dateStart = dateStart;
    }

    public String getDateEnd() {
        return dateEnd;
    }

    public void setDateEnd(String dateEnd) {
        this.dateEnd = dateEnd;
    }

    public int getKilometre() {
        return kilometre;
    }

    public void setKilometre(int kilometre) {
        this.kilometre = kilometre;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public String getPurpose() {
        return purpose;
    }

    public void setPurpose(String purpose) {
        this.purpose = purpose;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getStep() {
        return step;
    }

    public void setStep(String step) {
        this.step = step;
    }

    public String getCarNoId1() {
        return carNoId1;
    }

    public void setCarNoId1(String carNoId1) {
        this.carNoId1 = carNoId1;
    }

    public String getDateStart1() {
        return dateStart1;
    }

    public void setDateStart1(String dateStart1) {
        this.dateStart1 = dateStart1;
    }

    public String getCarNoId3() {
        return carNoId3;
    }

    public void setCarNoId3(String carNoId3) {
        this.carNoId3 = carNoId3;
    }

    public int getKilometreNum() {
        return kilometreNum;
    }

    public void setKilometreNum(int kilometreNum) {
        this.kilometreNum = kilometreNum;
    }

    public CarConfig getCarConfig() {
        return carConfig;
    }

    public void setCarConfig(CarConfig carConfig) {
        this.carConfig = carConfig;
    }

    public List<Map<String, Object>> getCarConfigList() {
        return carConfigList;
    }

    public void setCarConfigList(List<Map<String, Object>> carConfigList) {
        this.carConfigList = carConfigList;
    }

    public String getCarConfigId() {
        return carConfigId;
    }

    public void setCarConfigId(String carConfigId) {
        this.carConfigId = carConfigId;
    }

    public int getIsUse() {
        return isUse;
    }

    public void setIsUse(int isUse) {
        this.isUse = isUse;
    }
}
